package co.yixiang.yshop.module.infra.config;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 文件 URL 重写过滤器
 * 解决 Mixed Content 问题：将 HTTP 文件请求重定向到 HTTPS
 *
 * @author yshop
 */
@Slf4j
@Component
@Order(1) // 高优先级，在其他过滤器之前执行
public class FileUrlRewriteFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
            throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        String requestURI = httpRequest.getRequestURI();
        
        // 检查是否是文件下载请求且使用 HTTP 协议
        if (requestURI.startsWith("/admin-api/infra/file/") && 
            requestURI.contains("/get/") && 
            "http".equals(httpRequest.getScheme())) {
            
            // 构建 HTTPS 重定向 URL
            String redirectUrl = "https://ideawake.cn" + requestURI;
            
            log.info("[FileUrlRewriteFilter] 重定向 HTTP 文件请求: {} -> {}", requestURI, redirectUrl);
            
            // 执行 301 永久重定向
            httpResponse.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
            httpResponse.setHeader("Location", redirectUrl);
            return;
        }
        
        // 继续执行后续过滤器
        chain.doFilter(request, response);
    }
}
